home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 14295 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.1 KB

  1. Path: rain.fr!world-net!usenet
  2. From: Frederic LACHASSE <lachass@worldnet.fr>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: I need help please
  5. Date: Fri, 29 Mar 1996 20:37:51 +0000
  6. Organization: World-Net information exchange, Internet provider.
  7. Message-ID: <VA.00000074.00030e6a@fred>
  8. References: <4ja6n4$fh2@dfw-ixnews4.ix.netcom.com>
  9. Reply-To: lachass@worldnet.fr
  10. NNTP-Posting-Host: client144.sct.fr
  11. X-Newsreader: Virtual Access by Ashmount Research Ltd, http://www.ashmount.com
  12.  
  13. In article <4ja6n4$fh2@dfw-ixnews4.ix.netcom.com>, lewkbj@ix.netcom.com 
  14. (leonel wizel ) wrote:
  15. > I need some help please,
  16. > I have to write a writing check program, that takes the numbers for
  17. > example (112.43) and write as a:  one hundred and 43/100 output
  18. > I had the idea, and I thought had the algorithms, but the program that
  19. > I wrote does not work properly.  
  20. >     I need some help or suggestions of how to make this program work.
  21.  
  22. Most of your problems come from using double variables where you 
  23. actually need integers.
  24.  
  25. Short explanation: 1/3 cannot be represented by an exact decimal number 
  26. (0.3333333333 is just an approximation to the 10th decimal), so 
  27. computing 3 * (1/3) will probably give 0.9999999999 with a computer 
  28. using decimal floating point arithmetic with a precision of 10 digits.
  29.  
  30. Most micro-computers use *binary* floating point numbers and values like 
  31. 0.1 (1/10) cannot be represented exactly with a binary floating point 
  32. number. So expression like (x / 1000.0 * 1000.0 == x) are *not* 
  33. guaranteed to be true.
  34.  
  35. So the best course is to convert your number to integers as soon as 
  36. possible and do all your arithmetics with integers afterward.
  37.  
  38. So:
  39.  
  40.   double checkvalue;
  41.   cin >> checkvalue;
  42.   int amount = int(checkvalue + 0.001); // just help the thing to
  43.                                         // round properly
  44.   int change = int((checkvalue - amount) * 100.0 + 0.1);
  45.   
  46.   // Now use % and / on integer to do the job.
  47.  
  48. After that, you'll never have strange behavior from arithmetics. The 
  49. remaining bugs^H^H^H^Hproblems will be your complete responsability.
  50.  
  51. I hope this'll help.
  52.  
  53.  Frederic LACHASSE (ECP 86)
  54.  CompuServe: 100530,2005
  55.  Internet: lachass@worldnet.fr
  56.  
  57.